// components/MapView.vue
<template>
	<view class="map-wrapper">
		<div v-if="isH5" id="tmap-container" class="h5-map"></div>
		<map v-else :latitude="latitude" :longitude="longitude" :markers="markers" style="width: 100%; height: 100%" />
	</view>
</template>

<script>
import { TENCENT_MAP_KEY } from '@/common/map-key.js';

export default {
	data() {
		return {
			latitude: 0,
			longitude: 0,
			isH5: process.env.UNI_PLATFORM === 'h5',
			mapInstance: null,
			markers: []
		};
	},
	methods: {
		init() {
			if (this.isH5) {
				this.loadH5TencentMap();
			} else {
				this.loadMiniProgramTencentMap();
			}
		},
		loadH5TencentMap() {
			if (!window.TMap || !window.TMap.maps) {
				const script = document.createElement('script');
				script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${TENCENT_MAP_KEY}`;
				script.onload = () => {
					// 等 DOM 渲染完成，再执行地图初始化
					this.$nextTick(() => {
						setTimeout(() => {
							this.initH5Map(); // 注意不要立即执行
						}, 200); // 等待脚本完全注册
					});
				};
				document.head.appendChild(script);
			} else {
				this.initH5Map();
			}
		},
		initH5Map() {
			navigator.geolocation.getCurrentPosition(
				(pos) => {
					console.log(pos);
					this.latitude = pos.coords.latitude;
					this.longitude = pos.coords.longitude;
					// 定位成功后
					this.$emit('update-current-location', {
						lat: this.latitude,
						lng: this.latitude
					});
					const center = new TMap.LatLng(this.latitude, this.longitude);
					this.mapInstance = new TMap.Map(document.getElementById('tmap-container'), {
						center,
						zoom: 14
					});

					// 创建标记图层
					const markerLayer = new TMap.MultiMarker({
						map: this.mapInstance,
						geometries: [
							{
								id: 'marker-id', // 可选
								position: center,
								styleId: 'marker-style'
							}
						],
						styles: {
							'marker-style': new TMap.MarkerStyle({
								width: 25,
								height: 35,
								anchor: {
									x: 16,
									y: 32
								},
								src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
							})
						}
					});
				},
				(err) => {
					console.error('定位失败:', err);
				},
				{
					enableHighAccuracy: true
				}
			);
		},
		loadMiniProgramTencentMap() {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					console.log(res);
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					// 定位成功后
					this.$emit('update-current-location', {
						lat: this.latitude,
						lng: this.longitude
					});
					this.markers = [
						{
							id: 1,
							latitude: res.latitude,
							longitude: res.longitude,
							title: '当前位置',
							iconPath: '/static/img/location.png', // 请确保该图标存在，或使用内置图标
							width: 32,
							height: 32
						}
					];
				},
				fail: console.error
			});
		},
		//定位功能柜
		setCenterAndMarker(lat, lng, title) {
			// #ifdef H5
			if (!this.mapInstance || !TMap) {
				return;
			}

			const center = new TMap.LatLng(lat, lng);
			this.mapInstance.setCenter(center);

			// 清除旧图层（可选）
			if (this.markerLayer) {
				this.markerLayer.setMap(null);
			}

			// 创建新标记图层
			this.markerLayer = new TMap.MultiMarker({
				map: this.mapInstance,
				styles: {
					marker: new TMap.MarkerStyle({
						width: 16,
						height: 16,
						anchor: { x: 16, y: 16 },
						src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
					})
				},
				geometries: [
					{
						id: 'marker1',
						styleId: 'marker',
						position: center,
						properties: { title }
					}
				]
			});
			// #endif
			// #ifdef MP-WEIXIN
			this.latitude = lat;
			this.longitude = lng;
			this.markers = [
				{
					id: 1,
					latitude: lat,
					longitude: lng,
					title: title,
					iconPath: '/static/img/location.png',
					width: 32,
					height: 32
				}
			];
			// #endif
		}
	}
};
</script>

<style>
.map-wrapper,
#tmap-container,
map {
	width: 100%;
	height: 100vh;
}
</style>
